//---------------------------------------------------------------------------
//   Author: Chuck Kelly,
//           Monroe County Community College
//           http://www.monroeccc.edu/ckelly
//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop

#include "JoinF.h"
#include "net.h"

//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TJoinFrm *JoinFrm;

extern int          iPort;              // Port to receive on
extern DWORD        dwLength;           // Length of receiving buffer
extern WSADATA      wsd;
extern SOCKET       s;
extern char         *recvbuf;
extern char         *sendbuf;
extern int          ret;
extern DWORD        dwSenderSize;
extern SOCKADDR_IN  remote, local;
extern bool gameClient;                 // true when we are client
extern bool twoPlayer;                  // true for two player game
extern bool gameOn;                     // true when game is running
extern char message[80];                // status messages

SOCKADDR_IN server;                     // socket struct for server

//---------------------------------------------------------------------------
__fastcall TJoinFrm::TJoinFrm(TComponent* Owner)
        : TForm(Owner)
{
}

//---------------------------------------------------------------------------
void __fastcall TJoinFrm::FormActivate(TObject *Sender)
{
  JoinMemo->Clear();    // clear old messages
}

//---------------------------------------------------------------------------
void __fastcall TJoinFrm::JoinBtnClick(TObject *Sender)
{
  char localIP[16];     // storage for local IP address

  // ----- Initialize network stuff -----
  if (netInit() == NET_ERROR) {
    JoinMemo->Lines->Add(message);
    return;
  }

  // Setup network for use as a client
  if (setNetClient(ServerIP->Text.c_str()) == NET_ERROR) {
    JoinMemo->Lines->Add(message);        // display message
    return;
  }

  // Display the IP address of this machine
  strncpy(localIP,getLocalIP(),sizeof(localIP));
  sprintf(message, "Local IP address is %s", localIP);
  JoinMemo->Lines->Add(message);        // display message

  // set IP address
  local.sin_addr.s_addr = inet_addr(localIP);

  twoPlayer = false;    // network game
  gameClient = true;    // we are client

  // enable timer to attempt connection with server
  Timer1->Enabled = true;
}

//---------------------------------------------------------------------------
// Timer event attempts to connect with the server once per second.
// When a connection is established the game begins.
void __fastcall TJoinFrm::Timer1Timer(TObject *Sender)
{
  static bool connected = false;        // set true when connected to server

  // if not connected with game server
  if (!connected) {
    JoinMemo->Lines->Add("Attempting to connect with TANKS server.");

    // send our client ID to the server
    strncpy(sendbuf, CLIENT_ID, sizeof(CLIENT_ID));
    if ( sendData(sendbuf, sizeof(CLIENT_ID)) == NET_ERROR) {
      JoinMemo->Lines->Add(message);        // display message
      return;
    }

    // read SERVER_ID from server
    int readStatus = readData(recvbuf, sizeof(SERVER_ID));

    if (readStatus == NET_ERROR) {      // if read error
      JoinMemo->Lines->Add(message);    // display message
      return;
    } else if (readStatus == NET_OK) {  // if read was OK
      // if the server sent back the proper ID then we are connected
      if (strncmp(recvbuf, SERVER_ID, sizeof(SERVER_ID)) == 0) {
        JoinMemo->Lines->Add("Connected with TANKS server.");
        JoinMemo->Lines->Add("Waiting for server operator to start game.");
        Timer1->Interval = 100;         // speed up timer
        connected = true;               // we are connected to the server
      }
    }

  // else, we are connected with server
  } else {
    // Read SERVER_GO from server, SERVER_GO is sent when the server
    // operator presses the START button to begin the game.
    int readStatus = readData(recvbuf, sizeof(SERVER_GO));

    if (readStatus == NET_ERROR) {      // if read error
      JoinMemo->Lines->Add(message);    // display message
      return;
    } else if (readStatus == NET_OK) {  // if read OK
      // if the server sent back the proper start ID then the game has started
      if (strncmp(recvbuf, SERVER_GO, sizeof(SERVER_GO)) == 0) {
        gameOn = true;                    // begin game
        Timer1->Enabled = false;          // we're connected so stop looking
        Close();                          // close Join window
      }
    }
  }
}

//---------------------------------------------------------------------------
void __fastcall TJoinFrm::CancelBtnClick(TObject *Sender)
{
  if (gameClient) {
    Timer1->Enabled = false;    // stop looking for server
    closeSockets();
  }
  Close();
}

//---------------------------------------------------------------------------
void TJoinFrm::CloseSocket()
{
  if (gameClient) {            // if game server then close socket
    closeSockets();
  }
}

//---------------------------------------------------------------------------
void __fastcall TJoinFrm::FormClose(TObject *Sender, TCloseAction &Action)
{
  if (gameClient && !gameOn) {
    closeSockets();
  }
  Timer1->Enabled = false;    // stop looking for server
}
//---------------------------------------------------------------------------

